package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils;

import android.graphics.Bitmap;

import com.google.mlkit.vision.barcode.BarcodeScanner;
import com.google.mlkit.vision.barcode.BarcodeScanning;
import com.google.mlkit.vision.common.InputImage;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRCodeUtils {

    // 生产二维码
    public static Bitmap generateQRCode(String productId, int width, int height) throws WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            BitMatrix bitMatrix = qrCodeWriter.encode(productId, BarcodeFormat.QR_CODE, width, height);

            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    bitmap.setPixel(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 识别二维码
    // 方法：从 Bitmap 中读取二维码数据
    public static void readQRCodeFromBitmap(Bitmap bitmap, OnQRCodeReadListener listener) {
        if (bitmap == null || listener == null) {
            throw new IllegalArgumentException("Bitmap or listener cannot be null");
        }

        // 将 Bitmap 转换为 ML Kit 的 InputImage
        InputImage image = InputImage.fromBitmap(bitmap, 0);

        // 获取条码扫描器实例
        BarcodeScanner scanner = BarcodeScanning.getClient();

        // 处理图片并读取结果
        scanner.process(image)
                .addOnSuccessListener(barcodes -> {
                    if (!barcodes.isEmpty()) {
                        // 获取第一个二维码的值
                        String qrCodeValue = barcodes.get(0).getRawValue();
                        listener.onQRCodeRead(qrCodeValue);
                    } else {
                        listener.onQRCodeRead(null); // 没有读取到数据
                    }
                })
                .addOnFailureListener(e -> {
                    listener.onQRCodeRead(null); // 读取失败
                });
    }

    // 定义回调接口
    public interface OnQRCodeReadListener {
        void onQRCodeRead(String data);
    }

}
